'use strict';
const geoip = require('geoip-lite');

const { Service } = require('egg');
const {Op} = require("sequelize");
const dayjs = require("dayjs");
const ModelName = 'Order'
function createOrderNumber() {
  // 获取当前日期和时间
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1; // getMonth() 是从0开始的，所以需要+1
  let day = date.getDate();
  let hours = date.getHours();
  let minutes = date.getMinutes();
  let seconds = date.getSeconds();

  // 格式化日期和时间
  month = month < 10 ? '0' + month : month; // 如果月份小于10，前面添加一个0
  day = day < 10 ? '0' + day : day; // 如果日期小于10，前面添加一个0
  hours = hours < 10 ? '0' + hours : hours; // 如果小时小于10，前面添加一个0
  minutes = minutes < 10 ? '0' + minutes : minutes; // 如果分钟小于10，前面添加一个0
  seconds = seconds < 10 ? '0' + seconds : seconds; // 如果秒数小于10，前面添加一个0

  // 创建订单号
  return year + '' + month + '' + day + '' + hours + '' + minutes + '' + seconds;
}
function getOrderStatusMap(status, payment_status) {
  let statusMap = {
    status_value: '',
    status_name: ''
  }
  if (status === -1) {
    statusMap.status_value = 'canceled'
    statusMap.status_name = '已取消'
    return statusMap
  }
  if (status === 0) {
    statusMap.status_value = 'wait_pay'
    statusMap.status_name = '待付款'
    return statusMap
  }
  if (status === 1 && payment_status === 'paid') {
    statusMap.status_value = 'paid'
    statusMap.status_name = '已付款'
    return statusMap
  }
  // 退款完成
  if (status === 2 && payment_status === 'refunded') {
    statusMap.status_value = 'refunded'
    statusMap.status_name = '已退款'
    return statusMap
  }
  return statusMap
}
class RouterService extends Service {
    /**
     * 根据分页和搜索条件获取
     * @param {Object} where 查询用户的条件
     * @param {Number} page 当前分页
     * @param {Number} pageSize 当前页每页多少条
     */
    async getPage(where, page, pageSize) {
        return this.ctx.model[ModelName].findAndCountAll({
            where: {
                ...where,
                delete_flag: 0
            },
            offset: pageSize * (page - 1),
            limit: pageSize,
            order:[
                // id 降序
                ['create_time','DESC']
            ],
            include: [
                {
                    model: this.ctx.model.Ship,
                    as: 'ship',
                },
                {
                    model: this.ctx.model.Cycle,
                    as: 'cycle',
                },
                {
                    model: this.ctx.model.OrderUser,
                    as: 'userList',
                },
                {
                    model: this.ctx.model.User,
                    as: 'user',
                },
            ],
            distinct: true
        });
    }

    // 所有列表
    async allList() {
        return this.ctx.model[ModelName].findAll({
            order:[
                // id 降序
                ['create_time','DESC']
            ],
            include: [
              {
                model: this.ctx.model.Ship,
                as: 'ship',
              },
              {
                model: this.ctx.model.Cycle,
                as: 'cycle',
              },
              {
                model: this.ctx.model.OrderUser,
                as: 'userList',
              }
            ],
            where: {
                delete_flag: 0
            },
        });
    }
    async findOne(id) {
        return this.ctx.model[ModelName].findOne({
            where: {
                id,
            },
            include: [
                {
                    model: this.ctx.model.Ship,
                    as: 'ship',
                },
                {
                    model: this.ctx.model.Cycle,
                    as: 'cycle',
                },
                {
                    model: this.ctx.model.OrderUser,
                    as: 'userList',
                },
                {
                    model: this.ctx.model.User,
                    as: 'user',
                },
            ]
        });
    }
    async create(data) {
        // if (!data.userList || data.userList.length === 0) {
        //     throw new Error('请填写乘客信息')
        // }
        // 创建订单
        const order_no = createOrderNumber();
        let count = 0 // 余票
        let price = 0 // 成人价格
        let child_price = 0 // 儿童价格
        let order = null
        try {
            // 查找船班次
            const cycle = await this.ctx.model.Cycle.findOne({
                where: {
                    id: data.cycle_id
                },
                include: [
                    {
                        model: this.ctx.model.Ship,
                        as: 'ship',
                    }
                ]
            })
            // 当是三小时的需要判断预约的该时间段
            if (cycle.ship.code === 'THREE_HOUR') {
                const _ship = await this.ctx.model.Ship.findOne({
                    where: {
                        code: 'Custom'
                    }
                })
                if (_ship) {
                    let customList = await this.ctx.model.Cycle.findAll({
                        where: {
                            ship_id: _ship.id,
                            [Op.or]: [
                                // 情况1：新时间段的开始时间在已有时间段内
                                {
                                    start_time: { [Op.lte]: cycle.start_time },
                                    end_time: { [Op.gte]: cycle.start_time }
                                },
                                // 情况2：新时间段的结束时间在已有时间段内
                                {
                                    start_time: { [Op.lte]: cycle.end_time },
                                    end_time: { [Op.gte]: cycle.end_time }
                                },
                                // 情况3：新时间段完全包含已有时间段
                                {
                                    start_time: { [Op.gte]: cycle.start_time },
                                    end_time: { [Op.lte]: cycle.end_time }
                                }
                            ]
                        }
                    });
                    if (customList && customList.length > 0) {
                        throw new Error(`该时间段与${_ship.name}行程时间冲突，请联系客服处理`);
                    }
                }
            }
            if (!cycle) {
                throw new Error('船班次不存在')
            }
            // 余票
            count = cycle.count
            if (count < data.count) {
                throw new Error('余票不足，请重新选择')
            }
            // 先扣库存
            await this.ctx.model.Cycle.update({
                count: count - data.count
            }, {
                where: {
                    id: data.cycle_id
                }
            })
            try {
                const ip = this.ctx.request.headers['x-forwarded-for']?.split(',')[0] ||
                    this.ctx.request.headers['x-real-ip'] ||
                    this.ctx.request.ip ||
                    this.ctx.request.ips[0] ||
                    this.ctx.ip;
                const geo = geoip.lookup(ip);
                const country = geo ? geo.country : 'Unknown';
                // 获取请求头中的数据

                order = await this.ctx.model[ModelName].create({
                    ship_id: data.ship_id,
                    cycle_id: data.cycle_id,
                    count: data.count,
                    adult_count: data.adult_count || 0,
                    child_count: data.child_count || 0,
                    status: 0,
                    pay_status: 0,
                    total_price: data.totalPrice,
                    discount_amount: data.discount_amount || 0,
                    coupon_id: data.coupon_id,
                    amount: data.amount,
                    user_id: data.user_id,
                    role: data.role,
                    order_no,
                    id: order_no,
                    contact_name: data.contact_name,
                    contact_phone: data.contact_phone,
                    contact_email: data.contact_email,
                    contact_wx: data.contact_wx,
                    contact_remark: data.contact_remark,
                    ...data,
                    ...getOrderStatusMap(0, 'created'),
                    ip,
                    country,
                    lang: this.ctx.request.headers.lang || 'en',
                    start_time: cycle.start_time,
                    end_time: cycle.end_time,
                    duration: cycle.duration,
                    create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
                })
            } catch (e) {
                console.log(e)
                // 报错了，把库存加回来
                const _cycle = await this.ctx.model.Cycle.findOne({
                    where: {
                        id: data.cycle_id
                    },
                })
                await this.ctx.model.Cycle.update({
                    count: _cycle.count + data.count
                }, {
                    where: {
                        id: data.cycle_id
                    }
                })
                throw new Error('创建订单失败')
            }
        } catch (error) {
            console.log(error)
            throw new Error(error)
        }
        console.log('order',order)
        // 批量插入乘客信息
        const userList = data.userList.map(item => {
            return {
                order_id: order.dataValues.id,
                cycle_id: data.cycle_id,
                nickname: item.nickname,
                phone: item.phone,
                price: item.is_adult ? price : child_price,
                is_adult: item.is_adult,
            }
        })
        try {
            await this.ctx.model.OrderUser.bulkCreate(userList)
            return order
        } catch (e) {
            // 回滚库存
            await this.ctx.model.Cycle.update({
                count: count
            }, {
                where: {
                    id: data.cycle_id
                }
            })
            // 回滚订单
            await this.ctx.model[ModelName].destroy({
                where: {
                    id: order.dataValues.id
                }
            })
            console.log(e)
            throw new Error('创建订单失败')
        }
    }
    /**
     * 根据ID修改
     * @param {Number} id ID
     * @param {Object} data 要修改的信息
     */
    async update(id, data) {
        let _data = {
            ...data
        }
        if (data.payment_status && data.status !== undefined) {
            _data = {
                ...data,
                ...getOrderStatusMap(data.status, data.payment_status)
            }
        }
        return await this.ctx.model[ModelName].update(_data, { where: { id } });
    }
    /**
     * 根据id删除
     * @param {Number}
     */
    async deleteById(id) {
        return await this.update(id, { delete_flag: 1 });
    }
    // 校验订单是否存在
    async checkOrder(id) {
        return await this.ctx.model[ModelName].findOne({
            where: {
                id
            },
            include: [
                {
                    model: this.ctx.model.Ship,
                    as: 'ship',
                },
                {
                    model: this.ctx.model.Cycle,
                    as: 'cycle',
                },
            ]
        })
    }
  /**
   * status: INTEGER, // 订单状态0待支付、1已支付（待出票）2已出票（待开始）3 进行中 4已完成
   * pay_status: INTEGER, // 支付状态 0未支付 1已支付
   */
    // 取消
    async cancel(data) {
      const order = await this.checkOrder(data.id)
      if (!order) {
        throw new Error('订单不存在')
      }
      // 还原订单数量
      if (order.ship.code === 'Custom') {
          await this.ctx.service.cycle.deleteById(order.cycle_id);
      } else {
          await this.ctx.model.Cycle.update({
              count: Number(order.cycle.count) + Number(order.count)
          }, {
              where: {
                  id: order.cycle_id
              }
          })
      }
      // 取消订单
      await this.update(order.id, { status: -1, pay_status: 0, ...getOrderStatusMap(-1, 'created') })
    }
    // 退款
    async refund(data) {
      const order = await this.checkOrder(data.id)
      if (!order) {
        throw new Error('订单不存在')
      }
      // 退款
      return await this.update(order.id, { status: 5, ...getOrderStatusMap(5, 'paid') })
    }
}

module.exports = RouterService;
